package com.moli.iov.down.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.down.mapper.VehicleParamMapper;
import com.moli.iov.down.model.dto.req.VehicleParamDto;
import com.moli.iov.down.model.po.VehicleParam;
import com.moli.iov.down.service.IVehicleParamService;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.StringUtil;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 参数
 * </p>
 *
 * @author zql
 * @since 2019/9/17 17:12
 */
@Slf4j
@Service("vehicleParamService")
public class VehicleParamServiceImpl extends
    ServiceImpl<VehicleParamMapper, VehicleParam> implements
    IVehicleParamService {

  /**
   * 保存参数
   */
  @Override
  public boolean saveVehicleParam(VehicleParam vehicleParam) {
    return super.save(vehicleParam);
  }

  /**
   * 修改参数
   */
  @Override
  public boolean updateVehicleParam(VehicleParam vehicleParam) {
    QueryWrapper<VehicleParam> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("vin", vehicleParam.getVin());
    return super.update(vehicleParam, queryWrapper);
  }

  /**
   * 更新
   */
  @Override
  public boolean updateVehicleParam(VehicleParamDto vehicleParamDto) {

    QueryWrapper<VehicleParam> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("vin", vehicleParamDto.getVin());
    VehicleParam vehicleParam = getOne(queryWrapper, false);

    VehicleParam cpVehicleParam = new VehicleParam();
    CommonUtils.copyProperties(vehicleParamDto, cpVehicleParam);

    cpVehicleParam.setId(vehicleParam.getId());

    return updateById(cpVehicleParam);
  }

  /**
   * 查询单个参数
   */
  @Override
  public VehicleParam getVehicleParamByVin(String vin) {
    QueryWrapper<VehicleParam> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("vin", vin);
    return super.getOne(queryWrapper);
  }

  /**
   * 参数列表
   */
  @Override
  public List<VehicleParam> listVehicleParam(VehicleParamDto vehicleParamDto) {
    return super.list(assemblyConditions(vehicleParamDto));
  }

  /**
   * 组装查询条件
   */
  private QueryWrapper<VehicleParam> assemblyConditions(VehicleParamDto vehicleParamDto) {
    QueryWrapper<VehicleParam> queryWrapper = new QueryWrapper<>();

    if (vehicleParamDto == null) {
      return queryWrapper;
    }

    if (vehicleParamDto.getVins() != null && !vehicleParamDto.getVins().isEmpty()) {
      queryWrapper.in("vin", vehicleParamDto.getVins());
    }

    if(StringUtil.isNotBlank(vehicleParamDto.getVin())){
      queryWrapper.eq("vin", vehicleParamDto.getVin());
    }

    if(StringUtil.isNotBlank(vehicleParamDto.getDeviceId())){
      queryWrapper.eq("device_id", vehicleParamDto.getDeviceId());
    }
    queryWrapper.orderByDesc("gmt_create");
    return queryWrapper;
  }
}
